import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple
from decimal import Decimal

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_各学历及总体_省内就业城市分布(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None,
    education: Optional[str] = None
) -> Dict[str, Any]:
    """
    各学历及总体，省内就业城市分布 - 指标计算函数
    
    ## 指标说明
    该指标用于统计各学历毕业生在省内就业的城市分布情况，包括各城市就业人数及其占比。
    数据来源为学生客观数据表，根据就业省内外字段(job_around)筛选省内就业样本，
    并按就业城市(job_city)分组统计人数和占比。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        education (Optional[str]): 学历筛选条件，可选值: [本科毕业生，专科毕业生，硕士研究生，博士研究生]
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok", 
        "code": 0,
        "result": [
            {
                "group": "本科毕业生",
                "data": [
                    {"city": "成都市", "count": 1200, "percentage": 0.6},
                    {"city": "绵阳市", "count": 300, "percentage": 0.15}
                ],
                "total": 2000
            },
            {
                "group": "总体",
                "data": [
                    {"city": "成都市", "count": 2500, "percentage": 0.625},
                    {"city": "绵阳市", "count": 500, "percentage": 0.125}
                ],
                "total": 4000
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 各学历及总体，省内就业城市分布, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}")

        # 2. 计算 shard_tb_key
        shard_tb_key = re.sub(r'^[A-Za-z]*0*', '', client_code)
        logger.info(f"计算得到 shard_tb_key: {shard_tb_key}")

        # 3. 定义学历枚举
        educations = ["本科毕业生", "专科毕业生", "硕士研究生", "博士研究生"]
        if education and education not in educations:
            raise ValueError(f"学历参数必须为以下值之一: {educations}")

        # 4. 构建学历筛选条件
        education_conditions = educations if not education else [education]
        
        # 5. 查询各学历及总体数据
        result = []
        
        # 5.1 查询各学历数据
        for edu in education_conditions:
            # 查询该学历的省内就业总人数
            total_sql = f"""
            SELECT COUNT(*) as total 
            FROM dim_client_target_baseinfo_student_calc_{item_year} 
            WHERE shard_tb_key = %s 
            AND job_around = '省内就业' 
            AND education = %s
            """
            total_result = db.fetchone(total_sql, (shard_tb_key, edu))
            if not total_result or total_result['total'] == 0:
                continue
            
            total = total_result['total']
            
            # 查询各城市分布
            city_sql = f"""
            SELECT 
                job_city as city,
                COUNT(*) as count,
                COUNT(*) / %s as percentage
            FROM dim_client_target_baseinfo_student_calc_{item_year}
            WHERE shard_tb_key = %s
            AND job_around = '省内就业'
            AND education = %s
            GROUP BY job_city
            ORDER BY count DESC
            """
            city_results = db.fetchall(city_sql, (Decimal(total), shard_tb_key, edu))
            
            if city_results:
                city_data = [{
                    "city": row['city'],
                    "count": row['count'],
                    "percentage": float(row['percentage'])
                } for row in city_results]
                
                result.append({
                    "group": edu,
                    "data": city_data,
                    "total": total
                })
        
        # 5.2 查询总体数据(不区分学历)
        total_sql = f"""
        SELECT COUNT(*) as total 
        FROM dim_client_target_baseinfo_student_calc_{item_year} 
        WHERE shard_tb_key = %s 
        AND job_around = '省内就业'
        """
        total_result = db.fetchone(total_sql, (shard_tb_key,))
        
        if total_result and total_result['total'] > 0:
            total = total_result['total']
            
            city_sql = f"""
            SELECT 
                job_city as city,
                COUNT(*) as count,
                COUNT(*) / %s as percentage
            FROM dim_client_target_baseinfo_student_calc_{item_year}
            WHERE shard_tb_key = %s
            AND job_around = '省内就业'
            GROUP BY job_city
            ORDER BY count DESC
            """
            city_results = db.fetchall(city_sql, (Decimal(total), shard_tb_key))
            
            if city_results:
                city_data = [{
                    "city": row['city'],
                    "count": row['count'],
                    "percentage": float(row['percentage'])
                } for row in city_results]
                
                result.append({
                    "group": "总体",
                    "data": city_data,
                    "total": total
                })

        if not result:
            raise ValueError("未找到符合条件的省内就业数据")

        logger.info(f"指标 '各学历及总体，省内就业城市分布' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": result
        }

    except Exception as e:
        logger.error(f"计算指标 '各学历及总体，省内就业城市分布' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 各学历及总体，省内就业城市分布",
            "code": 500,
            "error": str(e)
        }